<template>
    <el-drawer v-model="knowsetDrawer" :modal="modal" :direction="direction" :size="getSize" :showClose="showClose"
        :before-close="handleClose" :modal-class="getModalClass" :class="getCustomClass">
        <template #header>
            <div class="drawer-title">{{ $t('message.text.libName') }}</div>
            <svg class="drawer-close" v-if="!showClose" @click="handleClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </template>
        <div class="know-set-body">
            <div class="nav-list">
                <el-scrollbar>
                    <div v-for="(item, index) in navList" :key="index" class="nav-item"
                        :class="[item.value == navActive.value && 'nav-active']" @click="changeNav(item)">
                        <svg class="nav-icon">
                            <use v-bind:xlink:href="`#${item.value != navActive.value ? item.icon : item.iconActive}`"></use>
                        </svg>
                        {{ $t(item.label) }}
                    </div>
                </el-scrollbar>
            </div>
            <div class="nav-body" v-loading="bodyLoading">
                <div class="nav-title">{{ $t(navActive.label) }}</div>
                <div class="nav-content">
                    <el-scrollbar max-height="calc(100vh - 187px)">
                        <div class="baseinfo-box" v-show="navActive.value == 'knowInfo'">
                            <el-form ref="knowFormRef" :model="knowForm" :rules="knowRules"
                                :disabled="!currentActiveAuth">
                                <div class="item-title">{{ $t('message.text.libName') }}</div>
                                <el-form-item prop="name">
                                    <el-input :placeholder="$t('message.placeholder.pleaseLibName')"
                                        v-model="knowForm.name"></el-input>
                                </el-form-item>
                                <div class="item-title">{{ $t('message.text.libDesc') }}</div>
                                <el-form-item prop="description">
                                    <el-input :placeholder="$t('message.placeholder.pleaseDesc')"
                                        v-model="knowForm.description" type="textarea"
                                        :autosize="{ minRows: 4, maxRows: 4 }"></el-input>
                                </el-form-item>
                                <div class="item-title">{{ $t('message.text.cover') }}</div>
                                <knowCover ref="knowCoverRef" :knowInfo="knowForm" @coverChange="coverChange">
                                </knowCover>
                            </el-form>
                        </div>
                        <div class="auth-box" v-show="navActive.value == 'auth'">
                            <template v-if="knowRole.length > 1">
                                <div class="item-title">{{ $t('message.text.sharSetting') }}</div>
                                <div class="role-box">
                                    <div class="role-item" v-for="(item, index) in roleList" :key="index"
                                        @click="changeRole(item)">
                                        <svg class="icon">
                                            <use
                                                v-bind:xlink:href="`#${knowForm.shareRole == item.value ? 'keowledge-mobile-xuanzhong' : 'keowledge-mobile-weixuanzhong'}`">
                                            </use>
                                        </svg>
                                        <span>{{ item.label }}</span>
                                    </div>
                                </div>
                                <div class="link-copy-url-box" v-if="knowForm.shareRole == 'all'">
                                    <div class="link-url-box" @dblclick="copyLink">
                                        {{ knowForm.linkUrl }}
                                    </div>
                                    <el-button type="primary" style="height:36px;"
                                        @click="copyLink">{{ $t('message.buttons.copyLink') }}</el-button>
                                </div>
                            </template>
                            <permissionRole ref="permissionRef" custom-class="sticky-header"
                                :disabled="!currentActiveAuth" :infoData="knowInfo" :role="persRoleList"
                                :roleType="knowInfo.roleType" :roleList="permRoleList"></permissionRole>
                        </div>
                        <div class="message-box" v-show="navActive.value == 'message'">
                            <message-push ref="messagePushRef" @changeMessageStatus="changeMessageStatus"
                                :knowForm="knowForm" :disabled="currentActiveAuth"></message-push>
                        </div>
                        <div class="trans-box" v-show="navActive.value == 'transtion'">
                            <div class="trans-title">{{ $t('message.text.transferTo') }}</div>
                            <el-autocomplete style="width:100%;margin-top:8px;" v-model="knowForm.transferUserName"
                                :fetch-suggestions="remoteMethod" :trigger-on-focus="false"
                                :placeholder="$t('message.placeholder.pleaseUserName')" :disabled="!currentActiveAuth"
                                @select="handleSelect" @change="transferChange">
                                <template #default="{ item }">
                                    <div class="custom-input-select">
                                        <img :src="item.headImg">
                                        <span>{{ item.realName }}</span>
                                    </div>
                                </template>
                            </el-autocomplete>
                            <!-- <el-select
                                style="width:100%;margin-top:8px;"
                                v-model="knowForm.transfer"
                                no-data-text="未找到该用户"
                                placeholder="请输入用户昵称"
                                filterable
                                remote
                                reserve-keyword
                                :remote-method="remoteMethod"
                                :loading="remoteLoading"
                            >
                                <el-option
                                    v-for="item in transOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select> -->
                        </div>
                    </el-scrollbar>
                </div>
                <div class="button-box" v-if="currentActiveAuth">
                    <el-button type="primary" @click="submit"
                        :loading="submitLoading">{{ $t('message.buttons.saveSetting') }}</el-button>
                    <el-button @click="handleClose">{{ $t('message.buttons.cancal') }}</el-button>
                </div>
            </div>
        </div>
    </el-drawer>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    computed,
    nextTick,
    getCurrentInstance
} from 'vue'

import { useRouter } from "vue-router"
const router = useRouter();
import type { FormInstance, FormRules } from 'element-plus'
import { getKnowUserRole, getAuthList, getDocAuthId } from '@/api/role'
import { getUserListPage, setLibrary } from '@/api/common'
import permissionRole from '@/views/common/permission.vue'
import messagePush from '@/views/common/messagePush.vue'
import { messageSave, messageIsPush } from '@/api/message'
import { $permissionRole } from '@/utils/role'
import knowCover from './cover.vue'
import { copyText } from '@/utils/util'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const emit = defineEmits(["update:knowInfo"])
const { proxy } = getCurrentInstance()
const knowsetDrawer = ref(false)
const knowCoverRef = ref()
const props = defineProps({
    direction: {
        type: String,
        default: 'rtl'
    },
    remove: Function,
    transtionBack: Function,
    hasModal: {
        type: Boolean,
        default: true
    },
    modalTrans: {
        type: Boolean,
        default: true
    },
    showClose: {
        type: Boolean,
        default: false
    },
    width: {
        type: [Number, String],
        default: '800px'
    },
    showHeaderBorder: {
        type: Boolean,
        default: true
    },
    knowInfo: {
        type: Object,
        default() {
            return {}
        }
    },
    changeVal: Function
})
const navList = ref([
    {
        label: 'message.tooltips.knowInfo',
        value: 'knowInfo',
        icon: 'keowledge-wenkuxinxi',
        iconActive: 'keowledge-a-wenkuxinxi1',
        authName: 'library_update'
    },
    {
        label: 'message.text.libPermission',
        value: 'auth',
        icon: 'keowledge-wenkuquanxian',
        iconActive: 'keowledge-a-wenkuquanxian1',
        authName: 'library_auth_settings'
    }, {
        label: 'message.text.messageSetting',
        value: 'message',
        icon: 'keowledge-xiaoximoban',
        iconActive: 'keowledge-a-xiaoximoban1',
        authName: 'library_remind_settings'
    },
    // {
    //     label:'页面设置',
    //     value:'page',
    //     icon:'',
    //     iconActive:''
    // },
    {
        label: 'message.text.knowTrans',
        value: 'transtion',
        icon: 'keowledge-a-zu4575',
        iconActive: 'keowledge-a-zu5056',
        authName: 'library_transfer'
    }
])
const navActive = ref({
    label: 'message.tooltips.knowInfo',
    value: 'knowInfo',
    icon: 'keowledge-wenkuxinxi',
    iconActive: 'keowledge-a-wenkuxinxi1',
    authName: 'library_update'
})
const bodyLoading = ref(false)
const knowFormRef = ref<FormInstance>()
const messagePushRef = ref()
const knowForm = ref({
    name: '',
    description: "",
    shareRole: 'user',
    color: '',
    linkUrl: '',
    addAuthConfigDto: [],
    type: "",
    id: '',
    readNotify: false,
    transfer: '',
    transferUserName: ''
})
const knowRules = ref<FormRules>({
    name: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (!value) {
                    callback(new Error($t('message.placeholder.pleaseLibName')))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
})
const knowRole = ref([])
const roleList = ref([])
const permRoleList = ref([])
const persRoleList = ref([])
const permissionRef = ref()
const getAuthorityFirst = ref(true)
const remoteLoading = ref(false)
const transOptions = ref([])
const submitLoading = ref(false)
const modal = computed(() => {
    return props.hasModal
})
const getSize = computed(() => {
    return props.width
})
const getModalClass = computed(() => {
    if (props.modalTrans) {
        return 'modal-trans'
    } else {
        ''
    }
})
const getCustomClass = computed(() => {
    let str = 'custom-knowset-drawer'
    if (props.showHeaderBorder) {
        str += ' show-drawer-border'
    }
    return str
})
onMounted(() => {
    init()
})
const currentActiveAuth = computed(() => {
    let flag = $permissionRole(navActive.value.authName, props.knowInfo.dcIdentifying)
    return flag
})
function init() {
    knowsetDrawer.value = true
    nextTick(() => {
        knowForm.value = Object.assign(knowForm.value, props.knowInfo)
        if (knowForm.value.shareRole == 'all') {
            knowForm.value.linkUrl = window.location.origin + '/#/knowledge/all/' + (props.knowInfo?.id || '')
        }
    })
}
function handleClose() {
    knowCoverRef.value.clearCover()
    knowsetDrawer.value = false
    if (props.remove) props.remove()
}
function submit() {
    switch (navActive.value.value) {
        case 'knowInfo':
            // 校验通过后执行
            knowFormRef.value.validate((valid) => {
                if (valid) {
                    submitLoading.value = true
                    let authObj = {
                        addAuthConfigDto: null
                    }
                    if (knowForm.value.addAuthConfigDto.length > 0) {
                        authObj.addAuthConfigDto = knowForm.value.addAuthConfigDto
                    }
                    setLibrary({
                        ...knowForm.value,
                        ...authObj
                    }).then(res => {
                        if (res.data.code == 0) {
                            proxy.$onePrompt.$oneNotify({
                                message: $t('message.message.updateKnowInfoSuccess'),
                                title: $t('message.prompt'),
                                type: "success",
                                position: 'bottom-right'
                            })
                            submitLoading.value = false
                            if (props.changeVal) props.changeVal(knowForm.value)
                        }
                    })
                }
            })
            break;
        case 'auth':
            getAuthData(true)
            break;
        case 'message':
            submitLoading.value = true
            let messageList = messagePushRef.value.getMessageList()
            messageList.forEach(element => {
                element.facilitator = element.messageType
                element.businessId = knowForm.value.id
            });
            messageSave(messageList, knowForm.value.id).then(res => {
                if (res.data.code == 0) {
                    if (knowForm.value.readNotify) {
                        proxy.$onePrompt.$oneNotify({
                            message: $t('message.message.saveMessageSuccess'),
                            title: $t('message.prompt'),
                            type: "success",
                            position: 'bottom-right'
                        })
                    }
                    submitLoading.value = false
                }
            })
            if (knowForm.value.readNotify != props.knowInfo.readNotify) {
                messageIsPush({
                    id: knowForm.value.id,
                    readNotify: knowForm.value.readNotify
                }).then(res => {
                    if (!knowForm.value.readNotify) {
                        proxy.$onePrompt.$oneNotify({
                            message: $t('message.message.closeMessage'),
                            title: $t('message.prompt'),
                            type: "success",
                            position: 'bottom-right'
                        })
                    }
                    if (props.changeVal) props.changeVal(knowForm.value)
                    submitLoading.value = false
                })
            }
            break;
        case 'page':

            break;
        case 'transtion':
            if (knowForm.value.transfer) {
                submitLoading.value = true
                setLibrary(knowForm.value).then(res => {
                    if (res.data.code == 0) {
                        proxy.$onePrompt.$oneNotify({
                            message: $t('message.message.transKnowSuccess'),
                            title: $t('message.prompt'),
                            type: "success",
                            position: 'bottom-right'
                        })
                        submitLoading.value = false
                        if (props.transtionBack) props.transtionBack()
                        if (props.remove) props.remove()
                    }
                })
            } else {
                proxy.$confirm($t('message.confirm.checkTransUser'), $t('message.text.knowTrans'), {
                    confirmButtonText: $t('message.buttons.submit'),
                    showCancelButton: false,
                    type: 'warning'
                })
            }
            break;
        default:
            break;
    }
}
function getAuthData(isSave = false) {
    const getPermissionData = permissionRef.value?.getPermissionData()
    knowForm.value.addAuthConfigDto = getPermissionData.role.map((item, index) => {
        let obj = {
            idcIdentifying: [],
            userInfoList: []
        }
        item.userInfoList.map((itemP, indexP) => {
            itemP.userId = itemP.id
            itemP.dataAuthType = itemP.type
        })
        obj.userInfoList.push(...item.userInfoList)
        obj.idcIdentifying.push(...item.idcIdentifying)
        return obj
    })
    persRoleList.value = knowForm.value.addAuthConfigDto
    if (isSave) {
        submitLoading.value = true
        setLibrary(knowForm.value).then(res => {
            if (res.data.code == 0) {
                proxy.$onePrompt.$oneNotify({
                    message: $t('message.message.savePermissionSuccess'),
                    title: $t('message.prompt'),
                    type: "success",
                    position: 'bottom-right'
                })
                submitLoading.value = false
            }
        })
    }
}
async function changeNav(item) {
    submitLoading.value = false
    if (navActive.value.value == 'auth') {
        getAuthData()
    }
    navActive.value = item
    if (item.value == 'auth') {
        bodyLoading.value = true
        if (getAuthorityFirst.value) {
            await getAuthority()
        } else {
            permissionRef.value.init()
        }
        await getAuthNameList()
        await getKnowRole()
    }
    if (item.value == 'message') {
        let userInfoList: any[] = []
        const permissionData = permissionRef.value.getPermissionData()
        permissionData.role.map((item: any, index: number) => {
            userInfoList.push(...item.userInfoList)
        })
        messagePushRef.value.setRoleList(userInfoList)
        messagePushRef.value.init()
    }
}
function getKnowRole() {
    roleList.value = [{
        label: $t('message.text.userDesc'),
        value: 'user',
        order: 0
    }]
    getKnowUserRole().then(res => {
        if (res.data.code == 0) {
            knowRole.value = res.data.data || []
            knowRole.value.forEach(item => {
                if (item == 'register') {
                    roleList.value.push({
                        label: $t('message.text.enterpriseDesc'),
                        value: 'register',
                        order: 1
                    })
                }
                if (item == 'all') {
                    roleList.value.push({
                        label: $t('message.text.wholeNetworkDesc'),
                        value: 'all',
                        order: 2
                    })
                }
            })
            roleList.value.sort((a, b) => {
                return a.order - b.order
            })
        }
    })
}
function getAuthority() {
    getDocAuthId(props.knowInfo.id).then(res => {
        if (res.data.code == 0) {
            persRoleList.value = res.data.data
        }
    }).finally(res => {
        bodyLoading.value = false
        getAuthorityFirst.value = false
        permissionRef.value.init()
    })
}
function getAuthNameList(type: any) {
    getAuthList({
        type: type
    }).then(res => {
        if (res.data.code == 0) {
            permRoleList.value = res.data.data
            nextTick(() => {
                permissionRef.value && permissionRef.value.init()
                bodyLoading.value = false
            })
        }
    }).catch(err => {
        bodyLoading.value = false
    })
}
function changeRole(item) {
    if (!currentActiveAuth.value) return
    knowForm.value.shareRole = item.value
    if (item.value == 'all') {
        knowForm.value.linkUrl = window.location.origin + '/#/view?id=' + (props.knowInfo?.id || '')
    }
}
function changeMessageStatus(item) {
    knowForm.value.readNotify = item.value
}
function remoteMethod(key: string, callback: (arg: any) => void) {
    // remoteLoading.value = true
    getUserListPage({
        key: key,
        size: 30,
        current: 1
    }).then(res => {
        if (res.data.code == 0) {
            // remoteLoading.value = false
            callback(res.data.data.records)
        }
    })
}
function handleSelect(item: Record<string, any>) {
    knowForm.value.transferUserName = item.realName
    knowForm.value.transfer = item.id
}
function transferChange() {
    if (!knowForm.value.transferUserName) {
        knowForm.value.transfer = ''
    }
}
function coverChange(form) {
    knowForm.value = form
}
// 双击触发复制连接功能
function copyLink() {
    copyText(knowForm.value.linkUrl, () => {
        proxy.$onePrompt.$oneNotify({
            title: $t('message.prompt'),
            message: $t('message.message.copyLinkSuccess'),
            position: "bottom-right",
            type: "success"
        })
    })
}
</script>
<style lang="scss">
.custom-knowset-drawer {
    .el-drawer__header {
        padding: 24px 24px 0px;
        margin-bottom: 16px;

        .drawer-title {
            font-size: 20px;
            color: #363b4c;
            @include SourceHanSansCN-Bold;
        }

        .drawer-close {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
    }

    .el-drawer__body {
        padding: 0px;

        .know-set-body {
            display: flex;
            height: 100%;
            width: 100%;

            .nav-list {
                width: 168px;
                height: 100%;
                background: #F5F6F7;
                padding: 23px 8px 0px;
                box-sizing: border-box;

                .nav-item {
                    border-radius: 4px;
                    height: 36px;
                    display: flex;
                    align-items: center;
                    font-size: 14px;
                    @include SourceHanSansCN-Regular;
                    color: #363b4c;
                    padding: 0px 16px;
                    box-sizing: border-box;
                    cursor: pointer;

                    .nav-icon {
                        width: 16px;
                        height: 16px;
                        margin-right: 8px;
                    }

                    &:hover {
                        background-color: #eeeff0;
                    }
                }

                .nav-item+.nav-item {
                    margin-top: 14px;
                }

                .nav-active {
                    background: #DDEAFF !important;
                    color: #1E6FFF;
                }
            }

            .nav-body {
                width: calc(100% - 168px);
                height: 100%;

                .nav-title {
                    font-size: 16px;
                    color: #363b4c;
                    @include SourceHanSansCN-Bold;
                    padding: 24px 24px 8px;
                }

                .nav-content {
                    .baseinfo-box {
                        padding: 0px 24px 16px;
                    }

                    .auth-box {
                        padding: 0px 24px 16px;

                        .role-box {
                            .role-item {
                                cursor: pointer;
                                display: flex;
                                align-items: center;
                                padding: 8px 0px;

                                .icon {
                                    width: 14px;
                                    height: 14px;
                                    margin-right: 12px;
                                }
                            }
                        }

                        .link-copy-url-box {
                            display: flex;
                            align-items: center;
                            padding-left: 22px;

                            .link-url-box {
                                width: 297px;
                                height: 36px;
                                line-height: 36px;
                                background: #F5F6F7;
                                border-radius: 6px 6px 6px 6px;
                                margin-right: 8px;
                                padding: 0px 12px;
                                overflow: hidden;
                                white-space: nowrap;
                                text-overflow: ellipsis;
                                cursor: pointer;
                            }
                        }
                    }

                    .message-box {
                        padding: 0px 24px 16px;

                        .message-type-box {
                            .message-item {
                                display: flex;
                                align-items: center;
                                font-size: 14px;
                                color: #363b4c;
                                @include SourceHanSansCN-Regular;

                                span {
                                    cursor: pointer;
                                }

                                .radio-icon {
                                    width: 14px;
                                    height: 14px;
                                    margin-right: 12px;
                                }
                            }

                            .message-item+.message-item {
                                margin-top: 8px;
                            }
                        }
                    }

                    .trans-box {
                        padding: 0px 24px 16px;

                        .trans-title {
                            font-size: 14px;
                            color: #363b4c;
                            @include SourceHanSansCN-Regular;
                        }
                    }
                }

                .item-title {
                    color: #363B4C;
                    font-size: 14px;
                    @include SourceHanSansCN-Bold;
                    margin-bottom: 8px;
                    margin-top: 16px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .title {
                        color: #363B4C;
                        font-size: 14px;
                        @include SourceHanSansCN-Bold;
                    }

                    .add-auth {
                        color: #1E6FFF;
                        @include SourceHanSansCN-Regular;
                        cursor: pointer;
                        display: flex;
                        align-items: center;
                        user-select: none;
                    }

                }

                .title-tips {
                    justify-content: start !important;

                    .tips {
                        color: #6F7588;
                        font-size: 12px;
                    }
                }

                .sticky-header {
                    position: sticky;
                    top: 0px;
                    margin: 0px;
                    padding: 16px 0px 8px;
                    background-color: #fff;
                    z-index: 9;
                }

                input::-webkit-input-placeholder {
                    @include SourceHanSansCN-Regular;
                }

                textarea::-webkit-input-placeholder {
                    @include SourceHanSansCN-Regular;
                }

                textarea {
                    box-shadow: none;
                    background: #f5f6f7;
                    resize: none;
                }

                .el-input__wrapper {
                    background: #F5F6F7 !important;
                    box-shadow: none !important;

                    input {
                        height: 32px !important;
                    }
                }

                .button-box {
                    padding: 14px 24px;
                }
            }
        }
    }
}

.custom-input-select {
    font-size: 14px;
    @include SourceHanSansCN-Regular;
    color: #494f6a;
    display: flex;
    height: 48px;
    align-items: center;

    img {
        width: 32px;
        height: 32px;
        border-radius: 6px;
        margin-right: 16px;
    }
}
</style>
<style lang="scss">
.baseinfo-box {
    .cover-box {
        .select-cover-box {
            .img-box {
                .el-scrollbar__view {
                    display: grid;
                    grid-template-columns: repeat(6, 1fr) !important;
                    flex-wrap: wrap;
                    grid-column-gap: 8px;
                    grid-row-gap: 8px;
                    padding-right: 8px;
                }
            }
        }
    }
}
</style>